package org.bonorsoft.modules.dingding.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.dingapi.DingdingRole;
import org.bonorsoft.common.exception.WilliamBootException;
import org.bonorsoft.common.util.DateUtils;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.dingding.entity.SysRole;
import org.bonorsoft.modules.dingding.entity.SysRoleDept;
import org.bonorsoft.modules.dingding.entity.SysRoleMenu;
import org.bonorsoft.modules.dingding.mapper.SysRoleDeptMapper;
import org.bonorsoft.modules.dingding.mapper.SysRoleMapper;
import org.bonorsoft.modules.dingding.mapper.SysRoleMenuMapper;
import org.bonorsoft.modules.dingding.service.ISysRoleService;
import org.bonorsoft.modules.dingding.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * @Description: 角色
 * @Author: WilliamYe
 * @Date:   2020-11-13
 * @Version: V1.0
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Override
    public void addRole(List<Integer> labelIdList) {
        List<SysRole> roleList = new ArrayList<>();
        for (Integer id:
                labelIdList) {
            try {
                String result = DingdingRole.getRole(id.longValue());
                SysRole role = JSONUtil.toBean(result, SysRole.class);
                role.setId(id);
                role.setCreateTime(DateUtils.getDate());
                roleList.add(role);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.saveOrUpdateBatch(roleList);
    }

    @Override
    public void deleteRole(List<Integer> labelIdList) {
        this.removeByIds(labelIdList);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) throws WilliamBootException{
        idList.forEach(item -> {
            Integer id = Integer.parseInt(item.toString());
            checkRoleAllowed(new SysRole(id));
            SysRole role = this.getById(id);
            if (userRoleService.countUserRoleByRoleId(id) > 0)
            {
                throw new WilliamBootException(String.format("%1$s已分配,不能删除", role.getName()));
            }
        });
        return roleMapper.removeByIds(idList);
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role)
    {
        if (StringUtils.isNotNull(role.getId()) && role.whetherAdmin())
        {
            throw new WilliamBootException("不允许操作超级管理员角色");
        }
//        if ("user".equals(role.getRoleSet()))
//        {
//            throw new BusinessException("普通用户不可进行数据权限分配");
//        }
    }

    /**
     * 根据条件校验角色名称是否唯一
     *
     * @param role 角色信息
     * @param condition 条件
     * @return 结果
     */
    @Override
    public String checkRoleUnique(String field, SysRole role, String condition)
    {
        Integer roleId = StringUtils.isNull(role.getId()) ? -1 : role.getId();
        SysRole info = checkRoleUnique(field, condition);
        if (StringUtils.isNotNull(info) && !info.getId().equals(roleId))
        {
            return UserConstants.ROLE_NAME_KEY_NOT_UNIQUE;
        }
        return UserConstants.ROLE_NAME_KEY_UNIQUE;
    }

    /**
     * 根据参数获取角色信息
     * @param field 字段名
     * @param condition 条件
     * @return 角色信息
     */
    private SysRole checkRoleUnique(String field, String condition) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(field, condition);
        return this.getOne(queryWrapper);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @param req
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(SysRole role, HttpServletRequest req)
    {
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getId());
        return insertRoleMenu(role, req);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userid 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRoleKeys(String userid) {
        List<SysRole> perms = roleMapper.selectRolesByUserId(userid);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询未删除的角色
     * @param roleId
     * @return
     */
    @Override
    public SysRole selectRoleById(Integer roleId) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).eq("id", roleId);
        return this.getOne(queryWrapper);
    }

    /**
     * 查看某用户的角色
     * @return
     * @param userid
     */
    @Override
    public List<SysRole> getRolesByUserId(String userid) {
        return roleMapper.getRolesByUserId(userid);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @param req
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role, HttpServletRequest req) {
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role, req);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     * @param req
     */
    public int insertRoleMenu(SysRole role, HttpServletRequest req)
    {
        String menuIds = req.getParameter("menuIds");
        String[] menuIdLists = menuIds.split(",");
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (String menuId : menuIdLists)
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     * @param req
     */
    private int insertRoleDept(SysRole role, HttpServletRequest req) {
        int rows = 1;
        String deptIds = req.getParameter("deptIds");
        if(oConvertUtils.isNotEmpty(deptIds)){
            String[] deptIdLists = deptIds.split(",");
            // 新增角色与部门（数据权限）管理
            List<SysRoleDept> list = new ArrayList<SysRoleDept>();
            for (String deptId : deptIdLists)
            {
                SysRoleDept rd = new SysRoleDept();
                rd.setRoleId(role.getId());
                rd.setDeptId(deptId);
                list.add(rd);
            }
            if (list.size() > 0)
            {
                rows = roleDeptMapper.batchRoleDept(list);
            }
        }
        return rows;
    }
}
